import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import '../base/Constant.dart';
import '../event/ProductContentEvent.dart';
import '../model/LoginUserBean.dart';

/// 存储工具类
/// //判断数据里面是否有这个key
//     if (!sp.containsKey(key)) {
//       return "";
//     }
//判断数据里面是否有这个值
//List list=[];
// var isAny = list.any((v){
//   return v==key;
// });
class Storage {
  static Future<void> setString(key, value) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(key, value);
  }

  static Future<String> getString(key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp.getString(key) ?? "";
  }

  static Future<void> remove(key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.remove(key);
  }

  static Future<void> clear() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.clear();
  }

  static Future<void> setLoginUser(LoginUserBean value) async {
    //value 转换成json
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString(SpKeys.USER_INFO, jsonEncode(value));
    sp.setString(SpKeys.USER_TOKEN, value.token.toString());
  }

  static Future<LoginUserBean?> getLoginUser() async {
    try {
      SharedPreferences sp = await SharedPreferences.getInstance();
      // json 转换成对象 LoginUserBean
      return LoginUserBean.fromJson(jsonDecode(sp.getString(SpKeys.USER_INFO)!));
    } catch (e) {
      return null;
    }
  }

  static Future<bool> isLoginUser() async {
    try {
      SharedPreferences sp = await SharedPreferences.getInstance();
      // json 转换成对象 LoginUserBean
      return sp.getString(SpKeys.USER_INFO) != null;
    } catch (e) {
      return false;
    }
  }

  static Future<void> loginOut() async {
    try {
      SharedPreferences sp = await SharedPreferences.getInstance();
      // json 转换成对象 LoginUserBean
      sp.remove(SpKeys.USER_INFO);
      sp.remove(SpKeys.USER_TOKEN);
      eventBus.fire(UserLoginEvent(false));
    } catch (e) {
      print(e);
    }
  }
}
